package com.ingrid.android;

import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.os.AsyncTask;

import com.ingrid.android.model.Item;

public class XMLTask extends AsyncTask<Void, Integer, Void> {

	public XMLCallback xmlCallback;
	public ArrayList<Item> itemList = new ArrayList<Item>();
	public String[] arrayTitles;
	private String rssURL;

	public XMLTask(XMLCallback xmlCallback, String rssURL) {
		this.xmlCallback = xmlCallback;
		this.rssURL = rssURL;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder documentBuilder;
			documentBuilder = documentBuilderFactory.newDocumentBuilder();
			Document document = documentBuilder.parse(this.rssURL);

			NodeList nodeList = document.getElementsByTagName("item");
			arrayTitles = new String[nodeList.getLength()];
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node nodeItem = nodeList.item(i);
				NodeList itemNodes = nodeItem.getChildNodes();
				Node itemTitle = itemNodes.item(0);
				Node itemLink = itemNodes.item(1);
				String title = itemTitle.getChildNodes().item(0).getNodeValue();
				String link = itemLink.getChildNodes().item(0).getNodeValue();

				Item item = new Item();
				item.setTitle(title);
				item.setUrl(link);

				arrayTitles[i] = item.getTitle();
				itemList.add(item);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

	@Override
	protected void onPostExecute(Void result) {
		this.xmlCallback.onXMLSucess(itemList, arrayTitles);
	}
}